// Lindsay Gilmour
// Adam Lusch
// Dan Niceswanger
//
// Computer Graphics Project 1:
// Asteroids!
// A Tribute

#include "Asteroid.h"

Asteroid::Asteroid(b2World* w, float32 x, float32 y, float32 s)
	: Thing(w, 1, MAGIC_NUMBER)
{
	scale = s;

	b2BodyDef bodyDef;
	bodyDef.position.Set(x, y);
	bodyDef.angularDamping = 0.1f / scale;
	body = world->CreateBody(&bodyDef);

	glNewList(baseDisplayList, GL_COMPILE);
	
	float32 dr = b2Random(-0.1f, 0.1f);
	float32 dg = b2Random(-0.1f, 0.1f);
	float32 db = b2Random(-0.1f, 0.1f);
	
	glColor3f(0.75f + dr, 0.5f + dg, 0.25f + db);
	glBegin(GL_LINE_LOOP);

	int32 divisions = (int)(12 * sqrt(scale));
	float32 step = 2.0f * M_PI / divisions;
	
	for (int32 i = 0; i < divisions; i++)
	{
		float32 size = scale * (b2Random(0.0f, 1.0f) + 1.5f);
			
		b2PolygonDef triDef;
		triDef.vertices[0] = b2Vec2(0, 0);
		triDef.vertices[1] = b2Vec2(size*cos(i*step), size*sin(i*step));
		triDef.vertices[2] = b2Vec2(size*cos((i+1)*step), size*sin((i+1)*step));
	
		glVertex2f(triDef.vertices[1].x, triDef.vertices[1].y);
		glVertex2f(triDef.vertices[2].x, triDef.vertices[2].y);		
		triDef.vertexCount = 3;
		triDef.density = 1.0f;
		triDef.friction = 0.0f;
		triDef.restitution = 0.995f;
		triDef.userData = this;
		body->CreateShape(&triDef);
		updateBoundingRadius(triDef);
	}

	glEnd();
	glEndList();

	body->SetMassFromShapes();
}

Asteroid::~Asteroid()
{
}

float32 Asteroid::getScale() const
{
	return scale;
}

void Asteroid::move()
{
	float32 magnitude = 6.0f * body->GetMass();
	
	float32 theta = b2Random(0.0f, 2.0f * M_PI);
	float32 fx = magnitude * cos(theta);
	float32 fy = magnitude * sin (theta);
	float32 torque = b2Random(0.0f, 100.0f);
	
	body->ApplyImpulse(b2Vec2(fx, fy), body->GetWorldPoint(b2Vec2(0.0f, 0.0f)));
	body->ApplyTorque(torque);
}

void Asteroid::draw()
{
	b2Vec2 position = body->GetPosition();
	float32 angle = body->GetAngle();

	glPushMatrix();
	
	glTranslatef(position.x, position.y, 0.0f);
	glRotatef(angle * 180.0f / M_PI, 0.0f, 0.0f, 1.0f);
	
	glLineWidth(2);
	
	glCallList(baseDisplayList);
	
	glPopMatrix();
}
